<!-- 用户资料页 -->
<template>
	<view class="uni-content">
		<view class="avatar">
			<uni-id-pages-avatar width="260rpx" height="260rpx"></uni-id-pages-avatar>
		</view>
		<uni-section title="个人信息" type="line"></uni-section>
		<uni-list>
			<uni-list-item class="item" @click="setNickname('')" title="昵称" :rightText="userInfo.nickname||'未设置'" link showArrow :show-extra-icon="true" :extra-icon="extraIcon_id">
			</uni-list-item>
			<uni-list-item class="item" @click="bindMobile" title="手机号" :rightText="userInfo.mobile||'未绑定'" link showArrow :show-extra-icon="true" :extra-icon="extraIcon_phone">
			</uni-list-item>
			<uni-list-item v-if="userInfo.email" class="item" title="电子邮箱" :rightText="userInfo.email">
			</uni-list-item>
			<uni-list-item v-if="hasPwd" class="item" @click="changePassword" title="修改密码" link showArrow :show-extra-icon="true" :extra-icon="extraIcon_password">
			</uni-list-item>
			<!-- 记录，修改密码、绑定手机号改为弹窗式 -->
		</uni-list>
		
		<uni-section title="关于APP" type="line" class="mt10"></uni-section>
		<uni-list >
			<uni-list-item class="item" @click="toAbout" title="关于好搭档微商城" rightText="公众号" link showArrow :show-extra-icon="true" :extra-icon="extraIcon_about">
			</uni-list-item>
			<uni-list-item class="item" @click="toReadme" title="在线文档" rightText="readMe.md" link showArrow :show-extra-icon="true" :extra-icon="extraIcon_md">
			</uni-list-item>
		</uni-list>
		
		<uni-list class="mt10">
			<image class="avatar1" :src="bg" mode="aspectFill" :draggable="false" />
			</uni-list>
		
		<!-- <uni-list class="mt700"> </uni-list> -->
		<uni-popup ref="dialog" type="dialog">
			<uni-popup-dialog mode="input" :value="userInfo.nickname" @confirm="setNickname" title="设置昵称"
				placeholder="请输入要设置的昵称">
			</uni-popup-dialog>
		</uni-popup>
		<uni-id-pages-bind-mobile ref="bind-mobile-by-sms" @success="bindMobileSuccess"></uni-id-pages-bind-mobile>
		<template v-if="showLoginManage">
			<button v-if="userInfo._id" @click="logout">退出登录</button>
			<button v-else @click="login">去登录</button>
		</template>
		
		<!-- 绑定手机号弹窗 -->
		<view>
			<uni-popup ref="bindphone" type="share" safeArea backgroundColor="#fff">
				<view class="uni-container" style="padding: 15px;">
					<uni-section title="绑定手机号" type="line"></uni-section>
					 	<view class="uni-content" style="background-color: #fff;">
						<match-media :min-width="690">
					 		<view class="login-logo">
					 			<image :src="logo"></image>
					 		</view>
					 		<!-- 顶部文字 -->
					 		<text class="title title-box">绑定手机号</text>
					 	</match-media>
					 	<!-- 登录框 (选择手机号所属国家和地区需要另行实现) -->
						<view style="margin-bottom: 10px;">
					 	<uni-easyinput clearable :focus="focusMobile" @blur="focusMobile = false" type="number" class="input-box" :inputBorder="false" v-model="phoneData.mobile"
					 		maxlength="11" placeholder="请输入手机号"  ></uni-easyinput>
					 	</view>
						<uni-id-pages-sms-form ref="smsForm" type="bind-mobile-by-sms" v-model="phoneData.code" :phone="phoneData.mobile">
					 	</uni-id-pages-sms-form>
					 	<button class="uni-btn send-btn-box" type="primary" @click="submitPhone" style="background-color: #f9bd10;margin-left: auto;margin-right: auto;">提交</button>
					 	<uni-popup-captcha @confirm="submitPhone" v-model="phoneData.captcha" scene="bind-mobile-by-sms" ref="popup">
					 	</uni-popup-captcha>
					 </view>
				</view>
			</uni-popup>
		</view>
		
		<!-- 修改密码弹窗 -->
		<view>
			<uni-popup ref="changePassword" type="share" safeArea backgroundColor="#fff">
				<view class="uni-container" style="padding: 15px;">
					<uni-section title="修改密码" type="line"></uni-section>
					 	<view class="uni-content" style="background-color: #fff;">
					 		<match-media :min-width="690">
					 			<view class="login-logo">
					 				<image :src="logo"></image>
					 			</view>
					 			<!-- 顶部文字 -->
					 			<text class="title title-box">修改密码</text>
					 		</match-media>
					 		<uni-forms ref="form" :value="passwordData" err-show-type="toast">
					 			<uni-forms-item name="oldPassword">
					 				<uni-easyinput :focus="focusOldPassword" @blur="focusOldPassword = false" class="input-box"
					 					type="password" :inputBorder="false" v-model="passwordData.oldPassword" placeholder="请输入旧密码">
					 				</uni-easyinput>
					 			</uni-forms-item>
					 			<uni-forms-item name="newPassword">
					 				<uni-easyinput :focus="focusNewPassword" @blur="focusNewPassword = false" class="input-box"
					 					type="password" :inputBorder="false" v-model="passwordData.newPassword" placeholder="请输入新密码">
					 				</uni-easyinput>
					 			</uni-forms-item>
					 			<uni-forms-item name="newPassword2">
					 				<uni-easyinput :focus="focusNewPassword2" @blur="focusNewPassword2 = false" class="input-box"
					 					type="password" :inputBorder="false" v-model="passwordData.newPassword2" placeholder="请再次输入新密码">
					 				</uni-easyinput>
					 			</uni-forms-item>
					 			<!-- <button class="uni-btn send-btn-box" type="primary" @click="submit">提交</button> -->
					 		    <button class="uni-btn send-btn-box" type="primary" @click="submitPassword()" style="background-color: #f9bd10;margin-left: auto;margin-right: auto;">提交</button>
							</uni-forms>
					 	</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>
<script>
	import mixin from '@/uni_modules/uni-id-pages/common/login-page.mixin.js';
	import passwordMod from '@/uni_modules/uni-id-pages/common/password.js'
	const db = uniCloud.database();
	const usersTable = db.collection('uni-id-users')
	const uniIdCo = uniCloud.importObject("uni-id-co")
	const uniIdCo2 = uniCloud.importObject("uni-id-co", {
			customUI:true
		})
  import {
    store,
    mutations
  } from '@/uni_modules/uni-id-pages/common/store.js'
	export default {
		mixins: [mixin],
    computed: {
      userInfo() {
        return store.userInfo
      },
	  tipText() {
	  	return `验证码已通过短信发送至 ${this.phoneData.mobile}。密码为6 - 20位`
	  }
    },
		data() {
			return {
				// 手机绑定 begin
				phoneData: {
					mobile: "",
					code: "",
					captcha: ""
				},
				focusMobile:true,
				logo: "/static/logo.png",
				// 手机绑定end
				// 修改密码begin
				focusOldPassword: false,
				focusNewPassword: false,
				focusNewPassword2: false,
				passwordData: {
							'oldPassword': '',
							'newPassword': '',
							'newPassword2': '',
						},
						rules: {
							oldPassword: {
								rules: [{
										required: true,
										errorMessage: '请输入新密码',
									},
									{
										pattern: /^.{6,20}$/,
										errorMessage: '密码为6 - 20位',
									}
								]
							},
				  ...passwordMod.getPwdRules('newPassword', 'newPassword2')
				},
				// 修改密码end
				univerifyStyle: {
					authButton: {
						"title": "本机号码一键绑定", // 授权按钮文案
					},
					otherLoginButton: {
						"title": "其他号码绑定",
					}
				},
				// userInfo: {
				// 	mobile:'',
				// 	nickname:''
				// },
				hasPwd:false,
				showLoginManage:false,//通过页面传参隐藏登录&退出登录按钮
				extraIcon_id: {
					color: '#2474b5',
					size: '22',
					type: 'contact-filled'
				},
				extraIcon_phone: {
					color: '#2474b5',
					size: '22',
					type: 'phone-filled'
				},
				extraIcon_password: {
					color: '#2474b5',
					size: '22',
					type: 'gear-filled'
				},
				extraIcon_about: {
					color: '#2474b5',
					size: '22',
					type: 'pyq'
				},
				extraIcon_md: {
					color: '#2474b5',
					size: '22',
					type: 'info-filled'
				},
				bg:"https://th.bing.com/th/id/R.bc1866b37437f9277d3fb35590c9df0a?rik=w3tp1K6DsJgdRw&riu=http%3a%2f%2f5b0988e595225.cdn.sohucs.com%2fimages%2f20190612%2ffe8c257f16ca467fb97e93280e765fe5.jpeg&ehk=4EWlDYi1tYhcBc6JXbBfOwggbVUnF8icopRWehywLaA%3d&risl=&pid=ImgRaw&r=0",
			}
		},
		async onShow() {
			this.univerifyStyle.authButton.title = "本机号码一键绑定"
			this.univerifyStyle.otherLoginButton.title = "其他号码绑定"
		},
		async onLoad(e) {
			if(e.showLoginManage){
				this.showLoginManage = true//通过页面传参隐藏登录&退出登录按钮
			}
			//判断当前用户是否有密码，否则就不显示密码修改功能
			let res = await uniIdCo.getAccountInfo()
			this.hasPwd = res.isPasswordSet
		},
		methods: {
			submitPassword() {
				console.log("passwordData", this.passwordData);
				console.log('rules', this.rules);
				this.$refs.form.validate()
					.then(res => {
						let {
							oldPassword,
							newPassword
						} = this.passwordData
						uniIdCo.updatePwd({
								oldPassword,
								newPassword
							}).then(e => {
								console.log(e);
								uni.removeStorageSync('uni_id_token');
								uni.setStorageSync('uni_id_token_expired', 0)
								uni.redirectTo({
									url:'/uni_modules/uni-id-pages/pages/login/login-withpwd'
								})
							}).catch(e => {
								uni.showModal({
									content: e.message,
									showCancel: false
								});
							})
					}).catch(errors => {
						let key = errors[0].key
						key = key.replace(key[0], key[0].toUpperCase())
						console.log(key, 'focus' + key);
						this['focus' + key] = true
					})
			},
			/**
			 * 完成并提交
			 */
			submitPhone() {
				if(! /^1\d{10}$/.test(this.phoneData.mobile)){
					this.focusMobile = true 
					return uni.showToast({
						title: '手机号码格式不正确',
						icon: 'none'
					});
				}
				if(! /^\d{6}$/.test(this.phoneData.code)){
					this.$refs.smsForm.focusSmsCodeInput = true 
					return uni.showToast({
						title: '验证码格式不正确',
						icon: 'none'
					});
				}
				
				console.log(this.phoneData);
				const uniIdCo = uniCloud.importObject("uni-id-co")
				uniIdCo.bindMobileBySms(this.phoneData).then(e => {
					console.log(e);
					uni.showToast({
						title: e.errMsg,
						icon: 'none'
					});
					// #ifdef APP-NVUE
					const eventChannel = this.$scope.eventChannel; // 兼容APP-NVUE
					// #endif
					// #ifndef APP-NVUE
					const eventChannel = this.getOpenerEventChannel();
					// #endif
					mutations.setUserInfo(this.phoneData)
					uni.navigateBack()
				}).catch(e => {
					console.log(e);
					if (e.errCode == 'uni-id-captcha-required') {
						this.$refs.popup.open()
					}
				}).finally(e => {
					this.phoneData.captcha = ""
				})
			},
			toAbout(){
				uni.navigateTo({
					url: '/pages/ucenter/about/about',
				})
			},
			toReadme(){
				uni.navigateTo({
					url: '/pages/ucenter/readme/readme',
				})
			},
			login() {
				uni.navigateTo({
					url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd',
					complete: (e) => {
						console.log(e);
					}
				})
			},
      logout(){
        mutations.logout()
      },
      bindMobileSuccess(){
        mutations.updateUserInfo()
      },
			changePassword(){ 
				this.$refs.changePassword.open()
				// uni.navigateTo({
				// 	url: '/uni_modules/uni-id-pages/pages/userinfo/change_pwd/change_pwd',
				// 	complete: (e) => {
				// 		console.log(e);
				// 	}
				// })
			},
			bindMobile() {
				// #ifdef APP-PLUS
				uni.preLogin({
					provider: 'univerify',
					success: this.univerify(), //预登录成功
					fail: (res) => { // 预登录失败
						// 不显示一键登录选项（或置灰）
						console.log(res)
						// this.bindMobileBySmsCode()
						this.$refs.bindphone.open()
					}
				})
				// #endif

				// #ifdef MP-WEIXIN
				this.$refs['bind-mobile-by-sms'].open()
				// #endif

				// #ifdef H5
				//...去用验证码绑定
				// 打开新增页面
				this.$refs.bindphone.open()
				// this.bindMobileBySmsCode()
				// #endif
			},
			univerify() {
				uni.login({
					"provider": 'univerify',
					"univerifyStyle": this.univerifyStyle,
					success: async e => {
						console.log(e.authResult);
						uniIdCo.bindMobileByUniverify(e.authResult).then(res => {
							console.log(res);
              mutations.updateUserInfo()
						}).catch(e => {
							console.log(e);
						}).finally(e=>{
							console.log(e);
							uni.closeAuthView()
						})
					},
					fail: (err) => {
						console.log(err);
						if (err.code == '30002' || err.code == '30001') {
							this.bindMobileBySmsCode()
						}
					}
				})
			},
			bindMobileBySmsCode() {
        uni.navigateTo({
          url: './bind-mobile/bind-mobile'
        })
			},
			setNickname(nickname) {
				console.log(nickname);
        if (nickname) {
          mutations.updateUserInfo({nickname})
          this.$refs.dialog.close()
        } else {
          this.$refs.dialog.open()
        }
			},
			deactivate(){
				uni.navigateTo({
					url:"/uni_modules/uni-id-pages/pages/userinfo/deactivate/deactivate"
				})
			},
      async bindThirdAccount(provider) {
        const uniIdCo = uniCloud.importObject("uni-id-co")
        const bindField = {
          weixin: 'wx_openid',
          alipay: 'ali_openid',
          apple: 'apple_openid',
          qq: 'qq_openid'
        }[provider.toLowerCase()]

        if (this.userInfo[bindField]) {
          await uniIdCo['unbind' + provider]()
          await mutations.updateUserInfo()
        } else {
          uni.login({
            provider: provider.toLowerCase(),
            onlyAuthorize: true,
            success: async e => {
              const res = await uniIdCo['bind' + provider]({
                code: e.code
              })
              if (res.errCode) {
                uni.showToast({
                  title: res.errMsg || '绑定失败'
                })
              }
              await mutations.updateUserInfo()
            },
            fail: async (err) => {
              console.log(err);
              uni.hideLoading()
            }
          })
        }

      }
		}
	}
</script>
<style lang="scss" scoped>

	@import "@/uni_modules/uni-id-pages/common/login-page.scss";

	.uni-content {
		padding: 0;
		background-color: rgb(237,237,237);
	}

	/* #ifndef APP-NVUE */
	view {
		display: flex;
		box-sizing: border-box;
		flex-direction: column;
	}
	@media screen and (min-width: 690px) {
		.uni-content {
			padding: 0;
			max-width: 690px;
			margin-left: calc(50% - 345px);
			border: none;
			max-height: none;
			border-radius: 0;
			box-shadow: none;
		}
	}
	/* #endif */
	.avatar {
		align-items: center;
		justify-content: center;
		margin: 22px 0;
		width: 100%; 
	}
	
	.avatar1 {
		align-items: center;
		justify-content: center;
		margin-bottom:  0;
		width: 100%;
		// height: 100%;
	}

	.item {
		flex: 1;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}

	button {
		margin: 10%;
		margin-top: 40px;
		border-radius: 0;
		background-color: #FFFFFF;
		width: 80%;
	}

	.mt10{
		margin-top: 10px;
	}
	.mt700{
		margin-top: 700px;
	}
</style>
